#!/usr/bin/env python
# -*- coding: utf-8 -*-


import wx
import wx.lib.filebrowsebutton as fb
import wx.lib.intctrl
import logging
from video_generator import *

import about

import overlay
import phase
class AdvanceTextCtrl(wx.TextCtrl):
    def __init__ (self,parent,BindedRadio=None,**therest):
        wx.TextCtrl.__init__(self, parent, **therest )
        self._BindedRadio = BindedRadio
        self.Bind(wx.EVT_LEFT_DOWN , self.onClick, self )
        self.Bind( wx.EVT_KILL_FOCUS, self.onControlChanged, self )
        
                
    def onClick(self, event):
        #change the radio button according to selected TextCtrl
        if self._BindedRadio != None:
            self._BindedRadio.SetValue(True)
        event.Skip ()
        
    def onControlChanged(self, event):
        pass

#------------------------------------------------------------------------------------
class DirBrowseButton(fb.FileBrowseButton):
    def __init__(self, parent, id = -1,
                 pos = wx.DefaultPosition, size = wx.DefaultSize,
                 style = wx.TAB_TRAVERSAL,
                 labelText = 'Select a directory:',
                 buttonText = 'Browse',
                 toolTip = 'Type directory name or browse to select',
                 dialogTitle = '',
                 startDirectory = '.',
                 changeCallback = None,
                 dialogClass = wx.DirDialog,
                 newDirectory = False,
                 name = 'dirBrowseButton',
                 hook = None):
		fbrowse = fb.FileBrowseButton.__init__(self,parent, id, pos, size, style,
									  labelText, buttonText, toolTip,
									  dialogTitle, startDirectory,
									  changeCallback = changeCallback,
									  name = name)
		self.dialogClass = dialogClass
		self.newDirectory = newDirectory
		self.hook         = hook

    def OnBrowse(self, evt= None):
        style=0
        if self.hook:
          self.hook(evt)

        if not self.newDirectory:
          style |= wx.DD_DIR_MUST_EXIST

        dialog = self.dialogClass(self,
                                  message = self.dialogTitle,
                                  defaultPath = self.startDirectory,
                                  style = style)

        if dialog.ShowModal() == wx.ID_OK:
            self.SetValue(dialog.GetPath())
        dialog.Destroy()

#------------------------------------------------------------------------------------





#--------------------------------------------------------------------------
#Class for Actions and to select different tabs.
#--------------------------------------------------------------------------
class TabAction(wx.Notebook):
	#-----------------------------------------------------------------------
	def __init__(self, parent):
		self.edir = (os.path.abspath(os.path.dirname(sys.argv[0])))
		wx.Notebook.__init__(self, parent, id=wx.ID_ANY, style=wx.BK_DEFAULT)

		# Create the MetaData Tab
		self.MetaDataTab = overlay.TabPanel(self)
		self.AddPage(self.MetaDataTab, "MetaData Settings")

		# Create the Video Setting Tab
		self.VideoSettingsTab = overlay.TabPanel(self)
		self.AddPage(self.VideoSettingsTab, "Video Settings")

		#create overlay Tab
		self.overlayTab = overlay.Panel(self)
		self.AddPage(self.overlayTab, "Overlay Settings")

		VideoSettingsTab = self.VideoSettingsTab
		MetaDataTab = self.MetaDataTab


		#--------------------  Meta Data Tab Panel  ----------------------------------------------------------------

		#------------------------------------------------------------------------------------------------
		# Add Buttons: 1. Stop Video     2. Test Settings     3. Generate Video 
		#------------------------------------------------------------------------------------------------
		#Button for [Stop & End All Video Generation]
		VideoSettingsTab.StopButton = wx.Button(VideoSettingsTab, -1, 'Stop Videos Generation')
		VideoSettingsTab.StopButton.SetBackgroundColour('RED')
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.StopButton,pos=(0, 0),span=(1, 4),flag=wx.LEFT ,border=2)
		self.Bind(wx.EVT_BUTTON, self.StopVideoGenMsgShow,VideoSettingsTab.StopButton)

		#Button for [Test Settings for first 2 Videos]
		VideoSettingsTab.TestSettingsButton = wx.Button(VideoSettingsTab, -1, 'Test Videos Settings')
		VideoSettingsTab.TestSettingsButton.SetBackgroundColour('YELLOW')
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.TestSettingsButton,pos=(0,4),span=(1,5), flag=wx.TOP |wx.EXPAND ,border=2)
		self.Bind(wx.EVT_BUTTON, self.TestSettingsMsgShow,VideoSettingsTab.TestSettingsButton)

		#Button for [Test Settings & All Video Generation]
		VideoSettingsTab.GeneratVidsButton = wx.Button(VideoSettingsTab, -1, 'Generate Videos')
		VideoSettingsTab.GeneratVidsButton.SetBackgroundColour('GREEN')
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.GeneratVidsButton, pos=(0, 10),span=(1,5),flag=wx.TOP|wx.RIGHT  ,border=2)
		self.Bind(wx.EVT_BUTTON, self.StartVideosGenMsgShow,VideoSettingsTab.GeneratVidsButton)
		line = wx.StaticLine(VideoSettingsTab)
		VideoSettingsTab.Sizer.Add(line, pos=(1, 0), span=(1, 5),flag=wx.EXPAND|wx.BOTTOM, border=1)       
		text2 = wx.StaticText(VideoSettingsTab, label="Select files:")
		VideoSettingsTab.Sizer.Add(text2, pos=(2, 0), flag=wx.LEFT, border=1)
		line = wx.StaticLine(VideoSettingsTab)
		VideoSettingsTab.Sizer.Add(line, pos=(3, 0), span=(1, 5),flag=wx.EXPAND|wx.BOTTOM, border=1)       


		#------------------------------------------------------------------------------------------------
		#Buttons for File Browse
		#------------------------------------------------------------------------------------------------
		# image-input preroll Folder: _________ [browse]
		#------------------------------------------------------------------------------------------------
		# setup a mask accept only txt files as directed
		choiselist = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

		VideoSettingsTab.preroll  = phase.SelectButton(VideoSettingsTab,labelText ="preroll:      ",  startDirectory = os.getcwd())
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.preroll, pos=(5, 0), span=(1,20),flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL ,border=2)
		
		# main Folder Containing jpeg      : _________ [browse]
		VideoSettingsTab.main  = phase.SelectButton(VideoSettingsTab,labelText = "main:         ", hook = self.CallBackMain)
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.main, pos=(6, 0), span=(1,20),flag=wx.TOP|wx.LEFT|wx.BOTTOM | wx.EXPAND ,border=2)
		

		# close Folder Containing jpeg     : _________ [browse]
		VideoSettingsTab.close1  =  phase.SelectButton(VideoSettingsTab,labelText = "close1:       ",  hook = self.CallBackClose1)
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.close1, pos=(7, 0), span=(1,20),flag=wx.TOP|wx.LEFT|wx.BOTTOM | wx.EXPAND ,border=2)

		# close Folder Containing jpeg     : _________ [browse]
		VideoSettingsTab.close2  =  phase.SelectButton(VideoSettingsTab,labelText = "close2:       ",  hook = self.CallBackClose2,min_choice=13)
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.close2, pos=(8, 0),span=(1,20), flag=wx.TOP|wx.LEFT|wx.BOTTOM | wx.EXPAND, border=2)

		# audio Folder Containing audio files: _________ [browse]
		VideoSettingsTab.audio  =  DirBrowseButton(VideoSettingsTab, -1, labelText = "audio:        ",  hook = self.CallBackAudio)
		VideoSettingsTab.audio.SetBackgroundColour('DARKGRAY')
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.audio, pos=(9, 0),span=(1,20), flag=wx.TOP|wx.LEFT|wx.BOTTOM | wx.EXPAND , border=2)


		# completed video output Folder      : _________ [browse]   
		VideoSettingsTab.outputvideo  = DirBrowseButton(VideoSettingsTab, -1, labelText = "output video:",  hook = self.CallBackOutput)
		VideoSettingsTab.outputvideo.SetBackgroundColour('DARKGRAY')
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.outputvideo, pos=(10, 0), span=(1,20),flag=wx.TOP|wx.LEFT|wx.BOTTOM |wx.EXPAND ,border=2)

		#combo box
		VideoSettingsTab.NofImages = wx.StaticText(VideoSettingsTab, label="*Images from main to Use in each Video:")
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.NofImages, pos=(12, 0), flag=wx.TOP|wx.LEFT, border=1)

		VideoSettingsTab.NoofMainImageCount = wx.ComboBox(VideoSettingsTab, -1, value=choiselist[2],pos=(0, 0), choices=choiselist, style=wx.CB_READONLY)
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.NoofMainImageCount, pos=(12, 1),span = (1,2) , flag=wx.TOP|wx.EXPAND, border=2) 

		# radio button
		VideoSettingsTab.PrompToContinue = wx.StaticText(VideoSettingsTab, label="*Prompt To Continue:")
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.PrompToContinue, pos=(13, 0), flag=wx.TOP | wx.EXPAND | wx.RIGHT, border=2)

		VideoSettingsTab.Never = wx.RadioButton(VideoSettingsTab, label='Never')
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.Never, pos=(13,1), flag=wx.EXPAND , border=3) 
		VideoSettingsTab.After = wx.RadioButton(VideoSettingsTab, label='After')
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.After, pos=(13,2), flag=wx.EXPAND , border=3)
		VideoSettingsTab.Never.SetValue(True) 

		#if yes to prompt
		VideoSettingsTab.VideoCount = wx.lib.intctrl.IntCtrl(VideoSettingsTab)
		VideoSettingsTab.Sizer.Add(wx.StaticText(VideoSettingsTab, label=" Videos: "), pos=(14, 0),flag = wx.EXPAND | wx.RIGHT, border=2)
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.VideoCount, pos=(14,1),  flag= wx.EXPAND | wx.RIGHT, border=2)

		#combo box
		VideoSettingsTab.ThumbText = wx.StaticText(VideoSettingsTab, label="*Use Video Thumbnail on Generated Videos:  ")
		VideoSettingsTab.Sizer.Add(VideoSettingsTab.ThumbText, pos=(15, 0),flag=wx.TOP|wx.LEFT, border=2) 
		Thumbnail = wx.ComboBox(VideoSettingsTab,-1, value=choiselist[0],choices=choiselist,style=wx.CB_READONLY)
		VideoSettingsTab.Sizer.Add(Thumbnail, pos=(15, 1),  span = (1,5),flag=wx.TOP|wx.EXPAND, border=2) 
		#--------------------  End of Video Setting Tab Panel  ----------------------------------------------------------------
		  
		  
		  
		  
		   
		  
		#--------------------  Meta Data Tab Panel  ----------------------------------------------------------------
		  
		MetaDataInfoText = wx.StaticText(MetaDataTab, label="Meta Data Setting:")
		MetaDataTab.Sizer.Add(MetaDataInfoText, pos=(0, 0), flag=wx.LEFT, border=2)
		line3 = wx.StaticLine(MetaDataTab)
		MetaDataTab.Sizer.Add(line3, pos=(1, 0), span=(1, 15),flag=wx.EXPAND|wx.BOTTOM, border=1)       

		# Browse Button for meta data information which will be loaded from MetaData txt file.
		mask = "*.txt"
		MetaDataTab.fname  =  fb.FileBrowseButton(MetaDataTab, -1, labelText = " *Meta Data Input File: ",
									toolTip= "Type filename or click browse to choose file",
									dialogTitle = "Please Select a file",
									fileMask = mask,
									fileMode = wx.OPEN | wx.FD_CHANGE_DIR,  
									startDirectory = os.getcwd())
		#MetaDataTab.fname.SetFilename("test.txt")
		MetaDataTab.fname.SetBackgroundColour('DARKGRAY')
		MetaDataTab.Sizer.Add(MetaDataTab.fname, pos=(2, 0), span=(1,10),flag=wx.LEFT|wx.BOTTOM |wx.EXPAND ,border=5)
		  
		line4 = wx.StaticLine(MetaDataTab)
		MetaDataTab.Sizer.Add(line4, pos=(3, 0), span=(1, 5),flag=wx.EXPAND|wx.BOTTOM, border=2) 

		#Describe Radio Button      
		Title_radio         = wx.RadioButton(MetaDataTab, label="Title       ")
		self.MetaDataTab.Title_radio = Title_radio 
		Description_radio   = wx.RadioButton(MetaDataTab, label="Description ")
		self.MetaDataTab.Description_radio = Description_radio
		Keywords_radio      = wx.RadioButton(MetaDataTab, label="Keywords    ")
		self.MetaDataTab.Keywords_radio = Keywords_radio

		#Add tille 
		MetaDataTab.Sizer.Add(wx.StaticText(MetaDataTab, label="   *Title: "), pos=(4, 0) ,flag=wx.TOP, border=3)
		TitleText = AdvanceTextCtrl(MetaDataTab,BindedRadio=Title_radio)
		MetaDataTab.Sizer.Add(TitleText, pos=(5,0), span=(1, 5), flag=wx.LEFT | wx.EXPAND, border=5)
		self.MetaDataTab.TitleText = TitleText


		  
		#description:
		MetaDataTab.Sizer.Add(wx.StaticText(MetaDataTab,label="   *Description: "), pos=(6, 0),flag=wx.TOP, border=1)
		DescriptionText = AdvanceTextCtrl(MetaDataTab,BindedRadio=Description_radio,size=wx.Size(400,250), style=wx.DOUBLE_BORDER| wx.TE_MULTILINE)
		MetaDataTab.Sizer.Add(DescriptionText ,  pos=(7,0),   flag=wx.LEFT , border=10)
		self.MetaDataTab.DescriptionText = DescriptionText

		#You Tube KeyWord
		MetaDataTab.Sizer.Add(wx.StaticText(MetaDataTab, label="   *You Tubes Keywords "), pos=(9, 0) ,flag=wx.TOP, border=1)
		KeywordText = AdvanceTextCtrl(MetaDataTab,BindedRadio=Keywords_radio)
		MetaDataTab.Sizer.Add(KeywordText, pos=(10,0), span=(1, 5), flag=wx.LEFT | wx.EXPAND, border=5)
		self.MetaDataTab.KeywordText = KeywordText
		 
		# Add md1 to md4 buttons            
		MetaDataTab.Sizer.Add(wx.StaticText(MetaDataTab, label=" Insert: "), pos=(6, 1), span=(1, 5), flag=wx.TOP | wx.EXPAND | wx.RIGHT, border=2)

		md1 = wx.Button(MetaDataTab, label='md1', pos=(0,0 ))
		MetaDataTab.Sizer.Add(md1 ,  pos=(7,1),   flag=  wx.RIGHT , border=1)
		self.Bind(wx.EVT_BUTTON, self.md_button_cb,md1)
		self.MetaDataTab.md1 = md1

		md2 = wx.Button(MetaDataTab, label='md2', pos=(417,198 ))
		MetaDataTab.Sizer.Add(md2 , pos = (7,2)  ,flag= wx.RIGHT , border=1)
		self.Bind(wx.EVT_BUTTON, self.md_button_cb,md2)
		self.MetaDataTab.md2 = md2

		 
		md3 = wx.Button(MetaDataTab, label='md3', pos=(417,245 ))
		MetaDataTab.Sizer.Add(md3 , pos = (7,3)  ,flag= wx.RIGHT , border=1)
		self.Bind(wx.EVT_BUTTON, self.md_button_cb,md3)
		self.MetaDataTab.md3 = md3

		md4 = wx.Button(MetaDataTab, label='md4', pos=(417,295 )) 
		MetaDataTab.Sizer.Add(md4 ,  pos=(7,4),   flag=wx.TOP  | wx.RIGHT, border=1)
		self.Bind(wx.EVT_BUTTON, self.md_button_cb,md4)
		self.MetaDataTab.md4 = md4

		# radio button
		MetaDataTab.Sizer.Add(Title_radio, pos=(11, 0) ,flag=wx.EXPAND, border=0)
		MetaDataTab.Sizer.Add(Description_radio, pos=(12, 0), flag=wx.EXPAND,border=0) 
		MetaDataTab.Sizer.Add(Keywords_radio, pos=(13, 0) ,flag=wx.EXPAND, border=0)

		#Add Category 
		MetaDataTab.CategoryName = ["Autos & Vehicles",
					"Comedy",
					"Education",
					"Entertainment",
					"Film & Animation",
					"Gaming",
					"Howto & Style",
					"Music",
					"News & Politics",
					"People &Blog",
					"Pets & Animal",
					"Science & Technology",
					"Sports",
					"Travel & Events"]
		MetaDataTab.CategoryId = ["2","23","27","24","1","20","26","10","25","22","15","28","17","19"]
		 
		MetaDataTab.categoryBox = wx.ComboBox(MetaDataTab, -1,"News & Politics",choices=MetaDataTab.CategoryName, style=wx.CB_READONLY)
		MetaDataTab.Sizer.Add(wx.StaticText(MetaDataTab, label=" *Category: "),pos=(14, 0), flag=wx.TOP, border=1)
		MetaDataTab.Sizer.Add(MetaDataTab.categoryBox, pos=(15, 0),flag=wx.EXPAND, border=1)


		#checkbox1.Bind(wx.EVT_COMBOBOX, self.OnSelect) 
		#--------------------  End of Video settings Tab Panel  ---------------------------------------------------------

		#These variables communicate with video Generator thread
		self.video_generator = None 


	def CallBackMain(self,evt):
		self.VideoSettingsTab.main.startDirectory = self.VideoSettingsTab.preroll.GetValue()
		evt.Skip ()
	def CallBackClose1(self,evt):
		self.VideoSettingsTab.close1.startDirectory = self.VideoSettingsTab.main.GetValue()
		evt.Skip ()
	def CallBackClose2(self,evt):
		self.VideoSettingsTab.close2.startDirectory = self.VideoSettingsTab.close1.GetValue()
		evt.Skip ()
	def CallBackAudio(self,evt):
		self.VideoSettingsTab.audio.startDirectory = self.VideoSettingsTab.close2.GetValue()
		evt.Skip ()
	def CallBackOutput(self,evt):
		self.VideoSettingsTab.outputvideo.startDirectory = self.VideoSettingsTab.audio.GetValue()
		evt.Skip ()
   
	def StopVideoGenMsgShow(self, evt):
		dialog = wx.MessageDialog(None, 'Do you want to stop All video generation ?', 'Question', wx.OK |wx.CANCEL|wx.ICON_INFORMATION)
		result = dialog.ShowModal()
		#Destroy dialog
		dialog.Destroy()
		if result == wx.ID_OK:
			self.StopVideoGen()
			
	def StopVideoGen(self):
		if self.video_generator:
			self.video_generator.close()
			#self.video_generator.join()

	def TestSettingsMsgShow(self, evt):
		dialog = wx.MessageDialog(None, 'Do you want to test settings for first two videos ?', 'Question', wx.OK |wx.CANCEL|wx.ICON_INFORMATION)
		result = dialog.ShowModal()
		#Destroy dialog
		dialog.Destroy()
		if result == wx.ID_OK:
			self.TestSettings()

	def StartVideosGenMsgShow(self, evt):
		dialog = wx.MessageDialog(self, 'Do you want to start video generation ?', 'Question', wx.OK |wx.CANCEL|wx.ICON_INFORMATION)
		result = dialog.ShowModal()
		#Destroy dialog
		dialog.Destroy()
		if result == wx.ID_OK:
			self.GenerateVideo()

	#------------------------------------------------------------------------------------------------------
	# This function is responsible for parsing meta data text file & extract info which will be used videos.
	#------------------------------------------------------------------------------------------------------
	def md_button_cb(self, evt):
		btn = evt.GetEventObject()
		appendable_text = "{ click " + btn.GetLabelText() + " button }"
		
		if self.MetaDataTab.Title_radio.GetValue() == True:
			self.MetaDataTab.TitleText.WriteText(appendable_text)
			self.MetaDataTab.TitleText.SetFocus()
			self.MetaDataTab.TitleText.SetSelection(-2,-2)
		elif self.MetaDataTab.Description_radio.GetValue() == True:
			self.MetaDataTab.DescriptionText.WriteText(appendable_text)
			self.MetaDataTab.DescriptionText.SetFocus()
			self.MetaDataTab.DescriptionText.SetSelection(-2,-2)
		elif self.MetaDataTab.Keywords_radio.GetValue() == True:
			self.MetaDataTab.KeywordText.WriteText(appendable_text)
			self.MetaDataTab.KeywordText.SetFocus()
			self.MetaDataTab.KeywordText.SetSelection(-2,-2)
		evt.Skip ()

	def check_dir4image(self,directory,image_count):
		count = 0
		files = os.listdir(directory)
		for var in files:
			if var.endswith('.jpg') or var.endswith('.jpeg') or var.endswith('.JPG') or var.endswith('.JPEG'):
				count += 1
		if count < image_count:
			raise Exception('less image then needed')
	def check_mdip_file(self,fname):
		f = open(fname,"r")
		f.close()

	def TestPathSettings(self):
		error = 0
		#check for preroll directory
		preroll = self.VideoSettingsTab.preroll
		try:
			self.check_dir4image(preroll.GetValue(),1)
			preroll.SetBackgroundColour('DARKGREY')
		except:
			preroll.SetBackgroundColour('red')
			error = -1
		
		#check for main directory
		main = self.VideoSettingsTab.main
		try:
			self.check_dir4image(main.GetValue(),3)
			main.SetBackgroundColour('DARKGREY')
		except:
			main.SetBackgroundColour('red')
			error = -1

		#check for close1 directory
		close1 = self.VideoSettingsTab.close1
		try:
			self.check_dir4image(close1.GetValue(),1)
			close1.SetBackgroundColour('DARKGREY')
		except:
			pass

		#check for close2 directory
		close2 = self.VideoSettingsTab.close2
		try:
			self.check_dir4image(close2.GetValue(),1)
			close2.SetBackgroundColour('DARKGREY')
		except:
			close2.SetBackgroundColour('red')
			error = -1

		#check for audio directory
		audio = self.VideoSettingsTab.audio
		count = 0
		try:
			files = os.listdir(audio.GetValue())
			for var in files:
				if var.endswith('.wav') or var.endswith('.mp3'):
					count += 1
			if count < 1:
				raise Exception('Less audio then needed')
		except:
			audio.SetBackgroundColour('red')
			error = -1

	#check for output directory
		outputvideo = self.VideoSettingsTab.outputvideo
		try:
			files = os.listdir(outputvideo.GetValue())
			outputvideo.SetBackgroundColour('DARKGREY')
		except:
			outputvideo.SetBackgroundColour('red')
			error = -1
			
		#Check metadata 
		try:
			fname = self.MetaDataTab.fname
			self.check_mdip_file(fname.GetValue())
			self.MetaDataTab.fname.SetBackgroundColour("darkgrey")
		except:
			self.MetaDataTab.fname.SetBackgroundColour("red")		
			error = -1
		self.Refresh()

		if error == -1:
			raise

	def TestSettings(self):

		try:
			preroll = self.VideoSettingsTab.preroll.GetValue()
			preroll = os.path.abspath(preroll)
			preroll_min = int(self.VideoSettingsTab.preroll.min.GetValue())
			preroll_max = preroll_min + int(self.VideoSettingsTab.preroll.var.GetValue())


			main    = self.VideoSettingsTab.main.GetValue()
			main = os.path.abspath(main)
			main_min = int(self.VideoSettingsTab.main.min.GetValue())
			main_max = main_min + int(self.VideoSettingsTab.main.var.GetValue())

			close1  = self.VideoSettingsTab.close1.GetValue()
			if close1 != wx.EmptyString and len(close1) != 0:
				close1 = os.path.abspath(close1)
				close1_min = int(self.VideoSettingsTab.close1.min.GetValue())
				close1_max = close1_min + int(self.VideoSettingsTab.close1.var.GetValue())
			else:
				close1 = None
				close1_min = None
				close1_max = None
				



			close2  = self.VideoSettingsTab.close2.GetValue()
			close2 = os.path.abspath(close2)
			close2_min = int(self.VideoSettingsTab.close2.min.GetValue())
			close2_max = close2_min + int(self.VideoSettingsTab.close2.var.GetValue())

			audio = self.VideoSettingsTab.audio.GetValue()
			audio = os.path.abspath(audio)

			output_dir = self.VideoSettingsTab.outputvideo.GetValue()
			output_dir = os.path.abspath(output_dir)

			no_of_main_image = self.VideoSettingsTab.NoofMainImageCount.GetValue()
			no_of_main_image = int(no_of_main_image)

			mdfilename = self.MetaDataTab.fname.GetValue()

			#selected category
			category_selection = self.MetaDataTab.categoryBox.GetSelection()
			categoryID = self.MetaDataTab.CategoryId[category_selection]

			#Title
			Title = self.MetaDataTab.TitleText.GetValue()

			#Description
			Description = self.MetaDataTab.DescriptionText.GetValue()
			 
			#Keyword
			KeyWord = self.MetaDataTab.KeywordText.GetValue()

			overlayInfo = overlay.dInfo
			overlayInfo.color = self.overlayTab.color.GetColour().GetAsString(wx.C2S_HTML_SYNTAX)
			overlayInfo.color = overlayInfo.color.replace("#","0x")
			overlayInfo.color = int(overlayInfo.color,16)
			overlayInfo.shadowColor = self.overlayTab.shadowColor.GetColour().GetAsString(wx.C2S_HTML_SYNTAX)
			overlayInfo.shadowColor = overlayInfo.shadowColor.replace("#","0x")
			overlayInfo.shadowColor = int(overlayInfo.shadowColor,16)
			overlayInfo.shadowX = self.overlayTab.sliderX.GetValue()
			overlayInfo.shadowY = self.overlayTab.sliderY.GetValue()

			self.TestPathSettings()
		except Exception, e:
			self.Parent.SetStatusText("Please correct the Path Setting")
			logging.error("In correct path provided")
			logging.exception(e)
			return -1

		try:
			#start the thread so that Application remain responsive
			if (not self.video_generator) or (self.video_generator.isAlive() == False):
				self.video_generator = VideoGenerator(self,
					iteration=2,
					preroll=preroll,
					main=main,
					close1=close1,
					close2=close2,
					audio=audio,
					output_dir=output_dir,
					no_of_main_image=no_of_main_image,
					mdfilename=mdfilename,
					categoryID=categoryID,
					Title=Title,
					Description=Description,
					KeyWord=KeyWord,
					overlayInfo=overlayInfo,
					edir=self.edir,
					preroll_min=preroll_min,
					preroll_max=preroll_max,
					main_min=main_min,
					main_max=main_max,
					close1_min=close1_min,
					close1_max=close1_max,
					close2_min=close2_min,
					close2_max=close2_max)
		except Exception, e:
			self.Parent.SetStatusText("unable to generate video")
			logging.error("error in uploading video")
			logging.exception(e)
			return -1

    
	def GenerateVideo(self):
		try:
			preroll = self.VideoSettingsTab.preroll.GetValue()
			preroll = os.path.abspath(preroll)
			preroll_min = int(self.VideoSettingsTab.preroll.min.GetValue())
			preroll_max = preroll_min + int(self.VideoSettingsTab.preroll.var.GetValue())


			main    = self.VideoSettingsTab.main.GetValue()
			main = os.path.abspath(main)
			main_min = int(self.VideoSettingsTab.main.min.GetValue())
			main_max = main_min + int(self.VideoSettingsTab.main.var.GetValue())

			close1  = self.VideoSettingsTab.close1.GetValue()
			if close1 != wx.EmptyString and len(close1) != 0:
				close1 = os.path.abspath(close1)
				close1_min = int(self.VideoSettingsTab.close1.min.GetValue())
				close1_max = close1_min + int(self.VideoSettingsTab.close1.var.GetValue())
			else:
				close1 = None
				close1_min = None
				close1_max = None



			close2  = self.VideoSettingsTab.close2.GetValue()
			close2 = os.path.abspath(close2)
			close2_min = int(self.VideoSettingsTab.close2.min.GetValue())
			close2_max = close2_min + int(self.VideoSettingsTab.close2.var.GetValue())

			audio = self.VideoSettingsTab.audio.GetValue()
			audio = os.path.abspath(audio)

			output_dir = self.VideoSettingsTab.outputvideo.GetValue()
			output_dir = os.path.abspath(output_dir)

			no_of_main_image = self.VideoSettingsTab.NoofMainImageCount.GetValue()
			no_of_main_image = int(no_of_main_image)

			mdfilename = self.MetaDataTab.fname.GetValue()

			#selected category
			category_selection = self.MetaDataTab.categoryBox.GetSelection()
			categoryID = self.MetaDataTab.CategoryId[category_selection]

			#Title
			Title = self.MetaDataTab.TitleText.GetValue()

			#Description
			Description = self.MetaDataTab.DescriptionText.GetValue()
			 
			#Keyword
			KeyWord = self.MetaDataTab.KeywordText.GetValue()

			overlayInfo = overlay.dInfo
			overlayInfo.color = self.overlayTab.color.GetColour().GetAsString(wx.C2S_HTML_SYNTAX)
			overlayInfo.color = overlayInfo.color.replace("#","0x")
			overlayInfo.color = int(overlayInfo.color,16)
			overlayInfo.shadowColor = self.overlayTab.shadowColor.GetColour().GetAsString(wx.C2S_HTML_SYNTAX)
			overlayInfo.shadowColor = overlayInfo.shadowColor.replace("#","0x")
			overlayInfo.shadowColor = int(overlayInfo.shadowColor,16)
			overlayInfo.shadowX = self.overlayTab.sliderX.GetValue()
			overlayInfo.shadowY = self.overlayTab.sliderY.GetValue()

			self.TestPathSettings()
		except Exception, e:
			self.Parent.SetStatusText("Please correct the Path Setting")
			logging.error("In correct path provided")
			logging.exception(e)
			return -1

		try:
			#start the thread so that Application remain responsive
			if (not self.video_generator) or (self.video_generator.isAlive() == False):
				self.video_generator = VideoGenerator(self,
					iteration=-1,
					preroll=preroll,
					main=main,
					close1=close1,
					close2=close2,
					audio=audio,
					output_dir=output_dir,
					no_of_main_image=no_of_main_image,
					mdfilename=mdfilename,
					categoryID=categoryID,
					Title=Title,
					Description=Description,
					KeyWord=KeyWord,
					overlayInfo=overlayInfo,
					edir=self.edir,
					preroll_min=preroll_min,
					preroll_max=preroll_max,
					main_min=main_min,
					main_max=main_max,
					close1_min=close1_min,
					close1_max=close1_max,
					close2_min=close2_min,
					close2_max=close2_max)
		except Exception, e:
			self.Parent.SetStatusText("unable to generate video")
			logging.error("error in uploading video")
			logging.exception(e)
			return -1

	#------------------------------------------------------------------------------------------------------
	# This function is resposible for parsing meta data text file & extract info which will be used videos.
	#------------------------------------------------------------------------------------------------------
	def OnPageChanged(self, event):
		old = event.GetOldSelection()
		new = event.GetSelection()
		sel = self.GetSelection()
		event.Skip()

	def OnPageChanging(self, event):
		old = event.GetOldSelection()
		new = event.GetSelection()
		sel = self.GetSelection()
		event.Skip()
#--------------- End of Class ----------------------------------------------
   





#--------------------------------------------------------------------------
#Main Class .
#--------------------------------------------------------------------------
class MainClass(wx.Frame):
    
    def __init__(self, *args, **kwargs):
        super(MainClass, self).__init__(*args, **kwargs) 

        self.CreateStatusBar()    # A Statusbar in the bottom of the window    

        self.InitUI()
        self.SetIcon(wx.Icon(about.icon_file, wx.BITMAP_TYPE_ICO))
       
    def InitUI(self): 
        menubar    = wx.MenuBar() # Add menu bar
        # Create menus named as file, option, tools and help
        fileMenu   = wx.Menu()    # File menu
        optionMenu = wx.Menu()    # option menu
        toolsMenu  = wx.Menu()    # create a menu for tools
        helpMenu   = wx.Menu()    # create a menu for help

        # file menu
        fitem      = fileMenu.Append(wx.ID_EXIT, '&Quit', 'Quit application')
        
        # help menu
        menuHelp   = helpMenu.Append(wx.ID_ANY, "&How To Use", "How to use this program")  #add about menu item
        menuAbout   = helpMenu.Append(wx.ID_ABOUT, "&About", "About this Software")  #add about menu item
        
        # all these add to menu bar 
        menubar.Append(fileMenu,"&File")                           # Adding the "filemenu" to the MenuBar
        menubar.Append(helpMenu,"&Help")                           # Adding the "Help menu" to the MenuBar
        self.SetMenuBar(menubar)

        # Bind these menus to respective events
        self.Bind(wx.EVT_MENU, self.OnQuit, fitem)
        self.Bind(wx.EVT_MENU,about.AboutCB, menuAbout)
        self.Bind(wx.EVT_MENU,about.HelpCB, menuHelp)
        

        #class for tab actions 
        tabs = TabAction(self)
        #get screen resolution of system and set it to default
        if os.name == 'nt': 
            self.SetSize(((wx.DisplaySize()[0]), (wx.DisplaySize()[1]-50)))
        else:
            self.SetSize((wx.DisplaySize()[0], wx.DisplaySize()[1]))

        self.SetTitle(about.name+" v " + about.version)  # name for window
        #self.SetAutoLayout(1)
        self.Centre()
        self.Show(True)
        #---------------------------------End of initGUI---------------------------------------------------------

        
    def RadioButton(self, pos):
        # Bind this Button for back end work
        pass
   
    def CheckButton(self, pos):
        # Bind this Button for back end work
        pass
    
    def StopVideo(self):
        # Bind this Button for back end work
        pass

    def GenVideos(self):
        # Bind this Button for back end work
        pass

    # OnSelect function handlesthe categories seletcted by user
    def OnSelect(self, evt):
        i = evt.GetString()
        self.st.SetLabel(i)
   

    # GUI EVENTS
    def checkBtnClick(self, e):
        self.url.SetValue("kkkkkkkk") 
    def OnQuit(self, e):
        self.Close()

#--------------------------------------------------------------------------------------------------------------------------
# This is main rutine for front end
#--------------------------------------------------------------------------------------------------------------------------
def main():

	os.putenv('VGM_INSTALL_PATH',os.path.abspath(os.path.dirname(sys.argv[0]) ) )
	os.environ['VGM_INSTALL_PATH'] = (os.path.abspath(os.path.dirname(sys.argv[0]) ))
	try:
		ex = wx.App(False)
	except Exception, e:
		logging.exception(e)
		exit()
		
	try:
		MainClass(None)
	except Exception, e:
		logging.exception(e)
		exit()

	   
	try:
		ex.MainLoop()
	except Exception, e:
		logging.exception(e)
		exit()

logging.basicConfig(filename='debug.log',level=logging.DEBUG)
#--------------------------------------------------------------------------------------------------------------------------
# This is main routine for front end
#--------------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
    #logging.basicConfig(filename='debug.log',level=logging.DEBUG)
    main()
